package models

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/joho/godotenv"

	"github.com/bwmarrin/snowflake"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"jjqzplucky.site/sz-core/pkg/types"
)

type BaseModel struct {
	Id         uint64           `gorm:"primarykey" json:"id"`
	CreateTime *types.LocalTime `gorm:"autoCreateTime" json:"create_time"`
	CreatedBy  uint64           `json:"created_by"`
	UpdateTime *types.LocalTime `gorm:"autoUpdateTime" json:"update_time"`
	UpdatedBy  uint64           `json:"updated_by"`
	DeleteTime gorm.DeletedAt   `gorm:"index" json:"delete_time"`
	DeletedBy  uint64           `json:"deleted_by"`
}

var (
	DB   *gorm.DB
	node *snowflake.Node
)

func (m *BaseModel) BeforeCreate(tx *gorm.DB) (err error) {
	m.Id = uint64(node.Generate())
	fmt.Printf("before create %v\n", m)

	return
}

func (m *BaseModel) AfterFind(tx *gorm.DB) (err error) {
	return
}

func ConnectDatabase() (db *gorm.DB, err error) {
	node, err = snowflake.NewNode(1)
	if err != nil {
		log.Fatalf("Error creating node.%V\n", err)
		return
	}

	if err != nil {
		log.Fatalf("Error getting current path.%V\n", err)
		return
	}

	err = godotenv.Load("../../.env")
	if err != nil {
		log.Fatalf("Error loading.env file .%V\n", err)
		return
	}
	DbHost := os.Getenv("DB_HOST")
	DbPort := os.Getenv("DB_PORT")
	DbUser := os.Getenv("DB_USER")
	DbPass := os.Getenv("DB_PASS")
	DbName := os.Getenv("DB_NAME")

	//DbHost := "117.72.90.158"
	//DbPort := "3306"
	//DbUser := "root"
	//DbPass := "admin789"
	//DbName := "hospital"

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", DbUser, DbPass, DbHost, DbPort, DbName)

	file, err := os.OpenFile("../../gorm.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		panic("failed to create log file")
	}
	newLogger := logger.New(
		log.New(file, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             100 * time.Millisecond,
			LogLevel:                  logger.Info,
			IgnoreRecordNotFoundError: false,
			Colorful:                  true,
		},
	)

	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})
	if err != nil {
		log.Fatalf("Connect to database failed, %v\n", err)

	} else {
		log.Printf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", DbUser, DbPass, DbHost, DbPort, DbName)
	}
	return
}

type PageParam struct {
	Page     int `json:"page" form:"page"`
	PageSize int `json:"pageSize" form:"pageSize"`
	Total    int `json:"total" form:"total"`
}
